# Author ： chosen-yn

from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, \
    DestroyModelMixin
from .common_reponse import APIResponse


class CommonListModelMixin(ListModelMixin):
    def list(self, request, *args, **kwargs):
        res = super().list(request, *args, **kwargs)
        # 1 有分页的情况
        if self.paginator:
            return APIResponse(
                count=res.data.get('count'),
                next=res.data.get('next'),
                previous=res.data.get('previous'),
                results=res.data.get('results'),
            )
        # 2 没有分页的情况,直接返回
        return APIResponse(results=res.data)


class CommonCreateModelMixin(CreateModelMixin):
    def create(self, request, *args, **kwargs):
        res = super().create(request, *args, **kwargs)
        return APIResponse(result=res.data)  # {code:100,msg:成功,result:{新增成功的对象}}


class CommonRetrieveModelMixin(RetrieveModelMixin):
    def retrieve(self, request, *args, **kwargs):
        res = super().retrieve(request, *args, **kwargs)
        return APIResponse(result=res.data)


class CommonUpdateModelMixin(UpdateModelMixin):
    def update(self, request, *args, **kwargs):
        res = super().update(request, *args, **kwargs)
        return APIResponse(result=res.data)


class CommonDestroyModelMixin(DestroyModelMixin):
    def destroy(self, request, *args, **kwargs):
        res = super().destroy(request, *args, **kwargs)
        return APIResponse(msg='删除成功')


# 一般都是 查询所有数据 或者是 过滤数据 带缓存
from django.core.cache import cache
from utils.common_logger import logger


class CacheListModelMixin(ListModelMixin):
    cache_key = None

    def list(self, request, *args, **kwargs):
        assert self.cache_key, ('cache_key必须设值')
        # 1 先从缓存拿
        obj_list = cache.get(self.cache_key)
        # 2 拿不到再去数据库里拿数据
        if not obj_list:
            logger.info('去数据库取数据了...')
            res = super().list(request, *args, **kwargs)
            # 3 放到缓存
            obj_list = res.data
            cache.set('cache_banner_list', obj_list)  # 列表套字典
        return APIResponse(results=obj_list)
